package com.zxz.springbootredis.controller;
import com.zxz.springbootredis.entity.EnterpriseUser;
import com.zxz.springbootredis.repository.EnterpriseUserRepository;
import com.zxz.springbootredis.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("enterprise")
public class EnterpriseUserController {
    @Autowired
    private EnterpriseUserRepository enterpriseUserRepository;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    // 手机号格式校验
    private boolean isPhoneValid(String phone) {
        return phone != null && phone.matches("^1[3-9]\\d{9}$");
    }

    // 生成4位随机验证码
    private String generateCode() {
        return String.format("%04d", new Random().nextInt(10000));
    }

    @PostMapping("sendCode")
    public JsonResult sendCode(@RequestBody Map<String, String> param) {
        String phone = param.get("phone");
        if (!isPhoneValid(phone)) {
            return JsonResult.failed("手机号格式错误");
        }
        String code = generateCode();
        // 验证码存Redis，60秒过期
        stringRedisTemplate.opsForValue().set("code:" + phone, code, 60, TimeUnit.SECONDS);
        System.out.println("验证码：" + code + "（模拟短信发送）");
        return JsonResult.success("验证码已发送", code);
    }

    @PostMapping("register")
    public JsonResult register(@RequestBody Map<String, String> param) {
        String phone = param.get("phone");
        String accountName = param.get("accountName");
        String password = param.get("password");
        String code = param.get("code");

        // 手机号格式校验
        if (!isPhoneValid(phone)) {
            return JsonResult.failed("手机号格式错误");
        }
        // 手机号重复验证
        if (enterpriseUserRepository.existsByPhone(phone)) {
            return JsonResult.failed("手机号已存在");
        }
        // 账号名重复验证
        if (enterpriseUserRepository.existsByAccountName(accountName)) {
            return JsonResult.failed("账号名已存在");
        }
        // 验证码校验
        String redisCode = stringRedisTemplate.opsForValue().get("code:" + phone);
        if (redisCode == null || !redisCode.equals(code)) {
            return JsonResult.failed("验证码错误或已过期");
        }
        // 校验成功，清除Redis验证码
        stringRedisTemplate.delete("code:" + phone);
        // 密码加密
        String encryptedPwd = passwordEncoder.encode(password);
        // 保存用户
        EnterpriseUser user = new EnterpriseUser();
        user.setPhone(phone);
        user.setAccountName(accountName);
        user.setPassword(encryptedPwd);
        enterpriseUserRepository.save(user);
        // 注册成功提示
        return JsonResult.success("注册成功", null);
    }

    @PostMapping("login")
    public JsonResult login(@RequestBody Map<String, String> param) {
        String account = param.get("account");
        String password = param.get("password");

        // 登录账号非空验证
        if (account == null || account.trim().isEmpty()) {
            return JsonResult.failed("账号不能为空");
        }
        // 密码非空验证
        if (password == null || password.trim().isEmpty()) {
            return JsonResult.failed("密码不能为空");
        }
        // 查询用户（手机号/账号名登录）
        EnterpriseUser user = enterpriseUserRepository.findByPhoneOrAccountName(account, account);
        if (user == null) {
            return JsonResult.failed("账号不存在");
        }
        // 密码验证
        if (!passwordEncoder.matches(password, user.getPassword())) {
            return JsonResult.failed("密码错误");
        }
        // 生成Token
        String token = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(token, account, 30, TimeUnit.MINUTES);
        // 登录成功提示
        return JsonResult.success("登录成功", token);
    }
    //453156
}